package com.ricchieri.lazymodel;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.filter.TripFilter;
import com.ricchieri.model.Trip;
import com.ricchieri.service.interf.ITripService;

public class TripLazyDataModel extends LazyDataModel<Trip> {

	private static final long serialVersionUID = 4593253494642335825L;

	private List<Trip> trips;
	private ITripService tripService;
	private TripFilter tripFilter;
	
	public TripLazyDataModel(ITripService tripService, TripFilter tripFilter) {
		super();
		this.tripFilter = tripFilter;
		this.tripService = tripService;
	}
	
    @Override
    public Object getRowKey(Trip trip) {
        return trip.getId();
    }

    @Override
    public Trip getRowData(String tripId) {
        int id = Integer.valueOf(tripId);

        for (Trip trip : trips) {
            if(id == trip.getId()) {
                return trip;
            }
        }
        return null;
    }
    
	@Override
	public List<Trip> load(int startingAt, int maxPerPage, String sortField, 
			SortOrder sortOrder, Map<String, String> filters) {
		
		tripFilter.setSortField(sortField);
		tripFilter.setSortOrder(sortOrder.toString());
		
        if(getRowCount() <= 0) {
            setRowCount(getTripService().getAllTripCountByFilter(tripFilter));
        }
        
        if(getRowCount() == startingAt && getRowCount()  != 0) {
        	startingAt = startingAt - BusinessSettings.ROW_MAX_RESULT;
        }
        trips = getTripService().getAllTripPaginatedByFilter(tripFilter, startingAt);

        setPageSize(BusinessSettings.ROW_MAX_RESULT);
        
        return trips;
	}

	public List<Trip> getTrips() {
		return trips;
	}

	public void setTrips(List<Trip> trips) {
		this.trips = trips;
	}

	public ITripService getTripService() {
		return tripService;
	}

	public void setTripService(ITripService tripService) {
		this.tripService = tripService;
	}

	public TripFilter getTripFilter() {
		return tripFilter;
	}

	public void setTripFilter(TripFilter tripFilter) {
		this.tripFilter = tripFilter;
	}
}
